import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/training'
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import('../views/HomeView.vue'),
      meta: { requiresAuth: true, showTabBar: true }
    },
    {
      path: '/training',
      name: 'Training',
      component: () => import('../views/TrainingView.vue'),
      meta: { requiresAuth: true, showTabBar: true, tabIndex: 0 }
    },
    {
      path: '/coach',
      name: 'Coach',
      component: () => import('../views/CoachView.vue'),
      meta: { requiresAuth: true, showTabBar: true, tabIndex: 1 }
    },
    {
      path: '/mall',
      name: 'Mall',
      component: () => import('../views/MallView.vue'),
      meta: { requiresAuth: true, showTabBar: true, tabIndex: 2 }
    },
    {
      path: '/dynamic',
      name: 'Dynamic',
      component: () => import('../views/DynamicView.vue'),
      meta: { requiresAuth: true, showTabBar: true, tabIndex: 3 }
    },
    {
      path: '/notification',
      name: 'Notification',
      component: () => import('../views/NotificationView.vue'),
      meta: { requiresAuth: true, showTabBar: false }
    },
    {
      path: '/mine',
      name: 'Mine',
      component: () => import('../views/MineView.vue'),
      meta: { requiresAuth: true, showTabBar: true, tabIndex: 4 }
    },
    {
      path: '/verify',
      name: 'Verify',
      component: () => import('../views/VerifyView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/customer-service',
      name: 'CustomerService',
      component: () => import('../views/CustomerServiceView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/chatroom',
      name: 'ChatRoom',
      component: () => import('../views/ChatRoomView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/notification/:id',
      name: 'NotificationDetail',
      component: () => import('../views/NotificationDetailView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/dingtalk-callback',
      name: 'DingtalkCallback',
      component: () => import('../views/DingtalkCallback.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/service',
      name: 'Service',
      component: () => import('../views/Service.vue'),
      meta: { requiresAuth: false }
    }
  ],
})

// 路由守卫：检查登录状态
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果需要认证但未登录，跳转到登录页
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } 
  // 如果已登录访问登录页，跳转到首页
  else if (to.path === '/login' && token) {
    next('/')
  } 
  else {
    next()
  }
})

export default router
